{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 模块和包"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**模块**是一个包含所有你定义的函数和变量的文件，其后缀名是.py。模块可以被别的程序引入，以使用该模块中的函数等功能。\n",
    "\n",
    "把多个模块组织成文件层次，称之为**包**。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "time.time()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "Python 路径为： ['', '/Users/MacBook/notebook/python科学生态/课程准备', '/Users/MacBook/anaconda3/lib/python37.zip', '/Users/MacBook/anaconda3/lib/python3.7', '/Users/MacBook/anaconda3/lib/python3.7/lib-dynload', '/Users/MacBook/anaconda3/lib/python3.7/site-packages', '/Users/MacBook/anaconda3/lib/python3.7/site-packages/aeosa', '/Users/MacBook/anaconda3/lib/python3.7/site-packages/IPython/extensions', '/Users/MacBook/.ipython'] \n",
      "\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "print('\\n\\nPython 路径为：', sys.path, '\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello T\n"
     ]
    }
   ],
   "source": [
    "test.say_hello('T')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "sys.path 包含了一个 Python 解释器自动查找所需模块的路径的列表。\n",
    "\n",
    "当我们使用import语句的时候，Python解释器是怎样找到对应的文件的呢？\n",
    "\n",
    "这就涉及到Python的搜索路径，搜索路径是由一系列目录名组成的，Python解释器就依次从这些目录中去寻找所引入的模块。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import test_1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from test_2 import say_1,say_2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "say_1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from test_2 import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### from … import 语句\n",
    "Python 的 from 语句让你从模块中导入一个指定的部分到当前命名空间中，语法如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from modname import name1[, name2[, ... nameN]]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### from … import * 语句\n",
    "把一个模块的所有内容全都导入到当前的命名空间也是可行的，只需使用如下声明："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from modname import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这提供了一个简单的方法来导入一个模块中的所有项目。然而这种声明不该被过多地使用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__builtins__',\n",
       " '__cached__',\n",
       " '__doc__',\n",
       " '__file__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " 'say_1',\n",
       " 'say_2',\n",
       " 'say_3']"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dir(test_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "模块也是使用 python 标准库的方法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ein.tags": "worksheet-0",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "## Python标准库\n",
    "\n",
    "Python具有庞大的标准库，Python的标准库和Python语言核心一起构成的Python语言。Python提供了标准库各模块的官方文档（ https://docs.python.org/3/library ）以及使用指南（ https://docs.python.org/3.6/tutorial/stdlib.html ）。另外， *Doug Hellmann* 的网站*Python 3 Module of the Week*（ https://pymotw.com/3/ ）和他的书 *The Python 3 Standard Library by Example*（中文版《Python 3标准库》由机械工业出版社于2018年10月11日出版）都是非常有帮助的指南，其针对标准库模块展示了大量的代码实例。\n",
    "\n",
    "教材中展示的一些常用的标准库模块：\n",
    "\n",
    "* `collections.defaultdict` 创建包含键默认值的字典，其参数是一个函数（可以是lambda函数），返回赋给缺失键的值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a b Huh?\n"
     ]
    }
   ],
   "source": [
    "from collections import defaultdict\n",
    "d = defaultdict(lambda: 'Huh?')\n",
    "d['a'] = 'a'\n",
    "d['b'] = 'b'\n",
    "print(d['a'], d['b'], d['c'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defaultdict(<function __main__.no_idea()>, {'a': 'a', 'b': 'b', 'c': 'Huh?'})"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ein.tags": "worksheet-0",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "* `collections.Counter` 提供了计数器功能。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Counter({'a': 5, 'b': 2, 'c': 3, 'd': 5})"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from collections import Counter\n",
    "a = Counter('aaaaabbccc')\n",
    "b = Counter('abcddddd')\n",
    "a | b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ein.tags": "worksheet-0",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "另外，可以针对两个或多个计数器进行组合，其也支持类似集合元算的求交、并、差运算。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ein.tags": "worksheet-0",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "* `itertools` 迭代器函数，每次返回一项，并记住当前调用的状态。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "import itertools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "autoscroll": false,
    "ein.hycell": false,
    "ein.tags": "worksheet-0",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "a\n",
      "b\n"
     ]
    }
   ],
   "source": [
    "for item in itertools.chain([1, 2], ['a', 'b']):\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for item in itertools.cycle([1, 2]):\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for item in itertools.accumulate([1, 2, 3, 4]):\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "autoscroll": false,
    "ein.hycell": false,
    "ein.tags": "worksheet-0",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "for item in itertools.accumulate([1, 2, 3, 4], lambda x, y: x * y):\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ein.tags": "worksheet-0",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "* `pprint` 友好打印"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('test', [1, 2, 3, 'test', 4, 5], 'This is a string!', {'age': 23, 'gender': 'F'})\n"
     ]
    }
   ],
   "source": [
    "data = (\"test\", [1, 2, 3,'test', 4, 5], \"This is a string!\",\n",
    "        {'age':23, 'gender':'F'})\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('test',\n",
      " [1, 2, 3, 'test', 4, 5],\n",
      " 'This is a string!',\n",
      " {'age': 23, 'gender': 'F'})\n"
     ]
    }
   ],
   "source": [
    "from pprint import pprint\n",
    "pprint(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ein.tags": "worksheet-0",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "### 获取第三方Python代码\n",
    "\n",
    "* **Pypi** (https://pypi.python.org)\n",
    "* **Github** (https://github.com)\n",
    "* **ReadTheDocs** (https://readthedocs.org)\n",
    "* **activestate** (http://code.activestate.com/recipes/langs/python)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
